package com.kedou.sdk.ui.fragment;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.ActivityManager;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AnticipateOvershootInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.FragmentActivity;

import com.kedou.sdk.params.QuickRegisterResponseParams.QuickRegisterResponseData;
import com.kedou.sdk.ui.assist.OnFinishActivityListener;
import com.kedou.sdk.utils.IoUtils;
import com.kedou.sdk.utils.ToolsUtils;
import com.kedou.sdk.utils.WL;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * Created by Administrator on 2018/3/7.
 */

public class AccountDialogFragment extends BaseDialogFragment implements View.OnClickListener {

    private static final String TAG = AccountDialogFragment.class.getSimpleName();

    private static final int REQUEST_LOCATION_PERMISSION = 10;

    private TextView mUserAccountContent;
    private TextView mUserPasswordContent;
    private ImageView mScreenShotConntent;
    private Button mSaveScreenShotBtn;
    private Button mCloseWindowbBtn;

    private boolean isForbitScreenshot = false;

    public static AccountDialogFragment newInstance(Bundle bundle) {
        AccountDialogFragment fragment = new AccountDialogFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        if(!XmlUtils.isNeedPrivate()){
//            String permission = Manifest.permission.WRITE_EXTERNAL_STORAGE;
//            if (!ToolsUtils.checkAppSelfPermission(getContext().getApplicationContext(), permission)) {
//                requestPermissions(new String[]{permission}, REQUEST_LOCATION_PERMISSION);
//            }
//        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View contentView = doInflateContentView(inflater, container, getLayoutIdentifier("wan_activity_quick_register"));
        isForbitScreenshot = false;
        mUserAccountContent = contentView.findViewById(getViewIdentifier("activity_quick_register_account_content"));
        mUserPasswordContent = contentView.findViewById(getViewIdentifier("activity_quick_register_password_content"));
        mScreenShotConntent = contentView.findViewById(getViewIdentifier("activity_quick_register_screenshot"));
        mSaveScreenShotBtn = contentView.findViewById(getViewIdentifier("activity_quick_register_save_screenshot"));
        mSaveScreenShotBtn.setVisibility(View.GONE);
//        if(XmlUtils.isNeedPrivate()){
//        }
        mCloseWindowbBtn = contentView.findViewById(getViewIdentifier("activity_quick_register_enter_game"));

        mSaveScreenShotBtn.setOnClickListener(this);
        mCloseWindowbBtn.setOnClickListener(this);

        QuickRegisterResponseData data = getQuickRegisterData();
        if (data != null) {
            mUserAccountContent.setText(data.getName());
            mUserPasswordContent.setText(data.getPassword());
        }

        Configuration config = getResources().getConfiguration();
        if (Configuration.ORIENTATION_PORTRAIT != config.orientation) {
            WindowManager.LayoutParams params = getDialog().getWindow().getAttributes();
            params.gravity = Gravity.CENTER | Gravity.FILL;
        }

        return contentView;
    }

    private QuickRegisterResponseData getQuickRegisterData() {
        Bundle bundle = getArguments();
        if (bundle != null) {
            return bundle.getParcelable("quickRegister");
        }

        WL.i(TAG, "onInitData -----> intent is null");
        return null;
    }

    @Override
    public void onClick(View view) {
        if (view == mSaveScreenShotBtn) {
            startScreenShotOperate(mSaveScreenShotBtn);
        } else if (view == mCloseWindowbBtn) {
            nextToBindPhoneActivity();
        }
    }

    public void startScreenShotOperate(View view) {
        if (isForbitScreenshot) return;

        if (!ToolsUtils.checkAppSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            String message = getString(getStringIdentifier("hnssn_quick_write_external_storage"), getAppName());
            Toast.makeText(getContext(), message, Toast.LENGTH_LONG).show();
            return;
        }

        //解决目前在OPPO和VIVO手机，Android系统版本为5.1/5.1.1,API LEVEL:22手机出现大量SIGSEGV(SEGV_MAPERR)崩溃信号
        if(Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP_MR1 || !checkAvailMemorySize()){
            String message = getString(getStringIdentifier("hnssn_quick_write_external_storage_unsupport"));
            Toast.makeText(getContext(), message, Toast.LENGTH_LONG).show();
            return;
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss", Locale.US);
        String filename = sdf.format(new Date()) + ".png";

        File screenshotFile = new File(ToolsUtils.getExternalStorageDirectory(), "screenshot/" + filename);
        if (ToolsUtils.checkAndMakeStorageDirectory(screenshotFile)) {
            final View rootView = view.getRootView();
            rootView.destroyDrawingCache();
            rootView.setDrawingCacheEnabled(true);
            rootView.buildDrawingCache();
            Bitmap bitmap = rootView.getDrawingCache();
            if (bitmap != null) {
                startScreenShotAnimator(bitmap, screenshotFile);
            } else {
                WL.i(TAG, "screenshot is failed! bitmap is null.");
            }
        } else {
            WL.i(TAG, "screenshot is failed! Storage directory create failed.");
        }

    }

    private boolean checkAvailMemorySize(){
        ActivityManager am = (ActivityManager) getContext().getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        am.getMemoryInfo(mi);
        return mi.availMem > (512 * 1024 * 1024);
    }

    public void nextToBindPhoneActivity() {
        OnFinishActivityListener listener = getOnFinishActivityListener();
        if (listener != null) {
            listener.doFinishActivity(this);
        }
    }

    private void startScreenShotAnimator(final Bitmap bitmap, final File file) {
        mScreenShotConntent.setImageBitmap(bitmap);
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(mScreenShotConntent, "scaleX", 1.0f, 0.0f);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(mScreenShotConntent, "scaleY", 1.0f, 0.0f);
        ObjectAnimator alpha = ObjectAnimator.ofFloat(mScreenShotConntent, "alpha", 1.0f, 0.0f);

        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.setDuration(1500);
        animatorSet.setInterpolator(new AnticipateOvershootInterpolator(1.0f));
        animatorSet.play(scaleX).with(scaleY).with(alpha)/*.with(translate)*/;
        animatorSet.addListener(new AnimatorListenerAdapter() {

            @Override
            public void onAnimationStart(Animator animation) {
                isForbitScreenshot = true;
                mScreenShotConntent.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                mScreenShotConntent.setVisibility(View.GONE);
                isForbitScreenshot = false;
                new AsyncStorageScreenshotTask(bitmap, file).execute();
            }
        });
        animatorSet.start();
    }

    private OnFinishActivityListener getOnFinishActivityListener() {
        if (!isNullContext()) {
            FragmentActivity activity = getActivity();
            if (activity instanceof OnFinishActivityListener) {
                return (OnFinishActivityListener) activity;
            }
        }
        return null;
    }

    private class AsyncStorageScreenshotTask extends AsyncTask<Void, Integer, Void> {

        private final Bitmap bitmap;
        private final File storage;

        public AsyncStorageScreenshotTask(Bitmap bitmap, File storage) {
            this.bitmap = bitmap;
            this.storage = storage;
        }

        @Override
        protected Void doInBackground(Void... voids) {
            FileOutputStream out = null;
            boolean result = false;
            try {
                out = new FileOutputStream(storage);
                if(bitmap != null && !bitmap.isRecycled()){
                    result = bitmap.compress(Bitmap.CompressFormat.PNG, 80, out);
                }
                out.flush();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (result && !bitmap.isRecycled()) {
                    bitmap.recycle();
                }
                IoUtils.closeSilently(out);
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            if(!isNullContext() && isResumed()){
                Toast.makeText(getContext(), storage.getAbsolutePath(), Toast.LENGTH_LONG).show();
            }
        }
    }
}
